package day190421;

import java.util.Arrays;

/**
 * @Author: LI DUO
 * @Date: 2019/4/21 下午 05:35
 * @Version 1.0
 */
public class MajorityElement {
    public int majorityElement(int[] nums) {
        if (nums.length < 1) {
            return 0;
        }
        int count = 1;
        int max = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] == max) {
                count++;
            } else {
                count--;
                if (count == 0) {
                    max = nums[i + 1];
                }
            }
        }
        return max;
    }

    public int majorityElement2(int[] nums) {
        if (nums.length < 1) {
            return 0;
        }
        int count = 1;
        int color = 0;
        for (int i : nums) {
            if (color == i) {
                count ++;
            } else {
                count --;
            }
            if (count == 0) {
                color = nums[i];
                count ++;
            }
        }
        return color;
    }

    public int majorityElement3(int[] nums) {
        if (nums.length < 1) {
            return 0;
        }
        Arrays.sort(nums);
        return nums[nums.length/2];
    }
}
